import Vue from 'vue';
import {Message, MessageBox} from 'element-ui'
Vue.component(MessageBox.name, MessageBox, Message);

export const addLineAndCopy = () => {
  //markdown代码存放在pre code 标签对中
  let arr = document.querySelectorAll('pre code');

  arr.forEach((v) => {
    let lines = v.innerText.split('\n').length - 1;

    //添加有序列表
    let ol = document.createElement("ol");
    ol.className = 'code-line';

    v.parentNode.className = 'code-wrap';
    v.parentNode.appendChild(ol);

    for (let i = 0; i <= lines; i++) {
      let li = document.createElement("li");
      ol.appendChild(li);
    }
    //添加复制按钮
    let copy = document.createElement("i");
    copy.className = 'el-icon-document-copy copy';
    copy.title = '复制';
    v.parentNode.appendChild(copy);
    //监听复制按钮点击事件
    copy.addEventListener('click',function(e){
      let parent = e.target.parentNode;
      let code = parent.getElementsByTagName('code')[0];
      let text = code.innerText;
      let textarea = document.createElement("textarea");
      textarea.innerHTML = text;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand('Copy');
      Message.success('复制成功')
      document.body.removeChild(textarea);
    });
  });
};